<template>
  <el-tabs type="card" v-model="activeName" @tab-click="">
    <el-tab-pane label="管理班级" name="first" style="height: 780px !important;">

      <div class="main">
        <div class="topBlock">
          <el-button @click="insertHandleClass" size="medium" icon="el-icon-plus"
                     style="margin-left: 0px; "></el-button>
          <el-button @click="deleteByIds" size="medium" icon="el-icon-delete-solid"></el-button>
        </div>

        <div class="table">
          <el-table :data="handClassList.slice((currentPage - 1) * pageSize, currentPage * pageSize)" stripe
                    :header-cell-style="{'border': 'none',textAlign:'center'}"
                    :cell-style="{'border': 'true',textAlign:'center',}"
                    border
                    ref="multipleTable"
                    @selection-change="handleSelectionChange"
                    max-height="690"

          >
            <!--            多选框-->
            <el-table-column type="selection" width="51"/>
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="school.schoolName" label="学校名称"></el-table-column>
            <el-table-column prop="majorName" label="专业名称"></el-table-column>
            <el-table-column prop="school.level" label="学历"></el-table-column>
            <el-table-column prop="year" label="年级"></el-table-column>
            <el-table-column prop="classNum" label="班级">
              <template slot-scope="scope">{{ scope.row.classNum }}班</template>
            </el-table-column>
            <el-table-column prop="studentList" label="考生人数">
              <template slot-scope="scope">
                <a style="color:#409EFF;cursor:pointer" @click="viewStu(scope.row)"> {{
                    scope.row.studentList.length
                  }}人</a>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="操作" width="300">
              <template slot-scope="scope">
                <!--                <el-button-group>-->
                <el-button type="primary" @click="addExamById(scope.row.id)" size="mini" icon="el-icon-document">考试
                </el-button>
                <el-button @click="editById(scope.row.id)" size="mini" icon="el-icon-setting">编辑</el-button>
                <el-button @click="deleteById(scope.row.id)" size="mini" icon="el-icon-delete">删除</el-button>
                <!--                </el-button-group>-->
              </template>
            </el-table-column>

          </el-table>

        </div>


      </div>
      <div class="footers">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="prev, pager, next, total, sizes"
            :total="handClassList.length"
            :current-page="currentPage"
            :page-sizes="[12,20]"
        >
        </el-pagination>
      </div>


    </el-tab-pane>


    <!--    <el-tab-pane label="发起测试" name="second">6</el-tab-pane>-->

    <!--    编辑用户隐藏框-->
    <el-dialog
        title="编辑班级"
        :visible.sync="editDialogVisible"
        width="30%"
        center
    >
      <el-form :model="handleClass">


        <div class="qSearch">
          <div class="text"><span>学校名称:</span></div>
          <div class="input">
            <el-autocomplete style="width: 100%;"
                             class="my-autocomplete"
                             v-model="handleClass.school.schoolName"
                             :fetch-suggestions="querySearchSchool"
                             :placeholder="placeholder"
                             @select="handleSelectSchool"
                             @blur="checkHandleSchool"
                             @focus="resetCheckHandleSchool">

              <template slot-scope="{ item }">
                <div class="name">{{ item.schoolName }}</div>
                <span class="addr">{{ item.id }}</span>
              </template>
            </el-autocomplete>
          </div>
        </div>
        <!--        输入框带提示-->
        <div class="qSearch">
          <div class="text"><span>专业名称:</span></div>
          <div class="input">
            <el-autocomplete style="width: 100%;"
                             class="my-autocomplete"
                             v-model="handleClass.majorName"
                             :fetch-suggestions="querySearch"
                             :placeholder="placeholder"
                             @select="handleSelect"
                             @blur="checkHandle"
                             @focus="resetCheckHandle">

              <template slot-scope="{ item }">
                <div class="name">{{ item.subjectName }}</div>
                <span class="addr">{{ item.id }}</span>
              </template>
            </el-autocomplete>
          </div>
        </div>
        <el-form-item label="年级:" :label-width="formLabelWidth">
          <el-input v-model="handleClass.year" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="班级:" :label-width="formLabelWidth">
          <el-input v-model="handleClass.classNum" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false;">取 消</el-button>
                <el-button type="primary" @click="editHandleClose(handleClass)">确 定</el-button>
            </span>
    </el-dialog>

    <!--    添加用户隐藏框-->
    <el-dialog
        title="添加班级"
        :visible.sync="addDialogVisible"
        width="30%"
        center
    >
      <el-form :model="handleClass">

        <!--        @select="handleSelectSchool"-->
        <!--        @blur="checkHandleSchool"-->
        <!--        @focus="resetCheckHandleSchool"-->
        <div class="qSearch">
          <div class="text"><span>学校名称:</span></div>
          <div class="input">
            <el-autocomplete style="width: 100%;"
                             class="my-autocomplete"
                             v-model="handleClass.school.schoolName"
                             :fetch-suggestions="querySearchSchool"
                             :placeholder="placeholder"
                             @select="handleSelectSchool"
                             @blur="checkHandleSchool"
                             @focus="resetCheckHandleSchool"
            >

              <template slot-scope="{ item }">
                <div class="name">{{ item.schoolName }}</div>
                <span class="addr">{{ item.id }}</span>
              </template>
            </el-autocomplete>
          </div>
        </div>
        <!--        输入框带提示-->
        <div class="qSearch">
          <div class="text"><span>专业名称:</span></div>
          <div class="input">
            <el-autocomplete style="width: 100%;"
                             class="my-autocomplete"
                             v-model="handleClass.majorName"
                             :fetch-suggestions="querySearch"
                             :placeholder="placeholder"
                             @select="handleSelect"
                             @blur="checkHandle"
                             @focus="resetCheckHandle">

              <template slot-scope="{ item }">
                <div class="name">{{ item.subjectName }}</div>
                <span class="addr">{{ item.id }}</span>
              </template>
            </el-autocomplete>
          </div>
        </div>
        <el-form-item label="年级:" :label-width="formLabelWidth">
          <el-input v-model="handleClass.year" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="班级:" :label-width="formLabelWidth">
          <el-input v-model="handleClass.classNum" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addHandleClose(handleClass)">确 定</el-button>
      </span>
    </el-dialog>


    <!--    发起考试隐藏框-->
    <el-dialog
        title="发起考试"
        :visible.sync="addExamVisible"
        width="40%"
        center>

      <!--  内嵌选择试卷list-->
      <el-dialog
          width="30%"
          title="选择试卷"
          :visible.sync="addExamVisibleBody"
          center
          append-to-body>
        <el-table
            :header-cell-style="{'border': 'none',textAlign:'center'}"
            :cell-style="{'border': 'true',textAlign:'center',}"
            :data="paperList"
            style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="试卷描述">
                  <span>{{ props.row.paperDesc }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column type="index" label="序号"/>
          <el-table-column label="试卷标题" prop="paperTitle"/>
          <el-table-column prop="id" label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="primary"
                         @click="setExamIdAndTitle(scope.row.id,scope.row.paperTitle);addExamVisibleBody=false"
                         size="mini" icon="el-icon-folder-checked">选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>


      <!--      发起考试表单-->
      <el-form :model="examData">

        <el-form-item :label-width="formLabelWidth" label="测试名:"  >
          <el-input  style="width: 400px" v-model="examData.examName" autocomplete="off" placeholder="不指定则覆盖试卷名" ></el-input>
        </el-form-item  >

        <el-form-item label="时间段:" :label-width="formLabelWidth">
          <div class="block">
            <el-date-picker
                style="width: 400px"
                v-model="dateData"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="setDate"
                @clear="dateData=[]">
            </el-date-picker>
          </div>
        </el-form-item>

        <el-form-item label="开放预览时间:" :label-width="formLabelWidth">
          <div class="block">
            <el-date-picker
                style="width: 400px"
                v-model="viewTimeData"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期"
                @change="setViewTime"
            >
            </el-date-picker>
          </div>
        </el-form-item>

        <el-form-item label="试卷名称:" :label-width="formLabelWidth" style="">
          <el-input disabled style="width: 400px" v-model="examData.paperTitle" autocomplete="off"></el-input>
          <el-button style="margin-left: 20px" type="primary" size="medium" @click="addExamVisibleBody = true">选择试卷
          </el-button>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="addExamVisible=false;">取 消</el-button>
                <el-button type="primary" @click="addExam">确 定</el-button>
      </span>
    </el-dialog>

    <!--    查看考生列表隐藏框逻辑量-->
    <el-dialog
        title="考生列表"
        :visible.sync="viewStuVisible"
        width="30%"
        >
      <el-table :data="viewStuData">
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column prop="userName" label="姓名"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="viewStuVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </el-tabs>
</template>

<script>
import {
  delHandleClassByIdApi,
  delHandleClassByIdsApi,
  findByHandleClassId,
  getHandleClassApi, insertHandleClassApi,
  updateHandleClassApi
} from "@/api/handleClass";

import {subjectData, schoolInfo} from "@/utils/data";
import notification from "@/utils/notification";
import {getPaperListApi} from "@/api/paper";
import {addExamApi} from "@/api/Exam";
import {Storage} from '@/utils/localStorage'

const storage = new Storage();

export default {
  name: "ManageClassView",
  data() {
    return {
      // 默认展开第一个标签
      activeName: 'first',
      // 页面数据
      handClassList: [],
      //分页数据
      currentPage: 1, //初始页
      pageSize: 12, //    每页的数据
      //多选选中的数据
      multipleTable: [],
      //编辑框隐藏逻辑量
      editDialogVisible: false,
      addDialogVisible: false,
      //编辑框的输入框长度
      formLabelWidth: '110px',
      //编辑框数据回显
      handleClass: {
        id: '',
        teacherId: '',
        majorName: '',
        year: '',
        classNum: '',
        schoolId: '',
        school: '',
        studentList: ''
      },
      // majorName索引输入框  或subjectName
      subjectData: subjectData,
      checkMajor: false,
      placeholder: '请输入内容',

      //下拉索引的参数
      // schoolData导入固定数据
      schoolData: schoolInfo,
      // checkSchoolName判断是否匹配固定数据
      checkSchoolName: false,
      //在选定下拉索引的数据时不需要判断
      unSelectTemp: false,

      //发起考试的参数
      //发起考试的隐藏框逻辑量
      addExamVisible: false,
      //嵌套在内层的隐藏框
      addExamVisibleBody: false,
      //存储发起考试的表单数据
      examData: {
        examName:'',
        paperId: '',
        handleClassId: '',
        teacherId: '',
        startTime: '',
        endTime: '',
        viewTime: '',
        paperTitle: ''
      },
      //发起考试进行试题列表拉取
      paperList: [],
      //考试时间范围预设数据
      dateData: [],
      //开放时间预设
      viewTimeData: '',
      //查看考生列表的隐藏框逻辑量
      viewStuVisible: false,
      //查看学生列表的数据变量
      viewStuData:[]

    };
  },
  methods: {
    viewStu(row) {
      this.viewStuData=row.studentList
      this.viewStuVisible=true
      // 这里可以根据具体需求判断点击的元素
      // 例如，可以使用事件委托来判断点击的是哪一列
      // 然后执行相应的操作
      console.log('点击了表格中的一列');
      console.log(row);

    },
    //确认发起考试
    addExam() {
      if(!this.examData.examName){
        this.examData.examName = this.examData.paperTitle
      }
      addExamApi(this.examData).then(res => {
        if (res.data.code == 200) {
          // console.info("this.res", res.data.data)
          notification.ntfExamSuccess(this.examData);
          this.addExamVisible = false;
        } else {
          notification.ntfErr("错误", res.data.msg);
          this.addExamVisible = false;
        }
      })
    },
    //选定试卷后将paperId paperTitle
    setExamIdAndTitle(id, title) {
      this.examData.teacherId = storage.getItem("user").id;
      this.examData.paperId = id
      this.examData.paperTitle = title;
      console.info("examData", this.examData)
      // console.info(this.dateData)
    },
    //选定日期后将数据注入examData
    setDate() {
      if (this.dateData && this.dateData.length === 2) {
        this.examData.startTime = this.dateData[0]
        this.examData.endTime = this.dateData[1]

      } else {
        // 处理数组为空的情况
      }
    },
    setViewTime() {
      if (this.viewTimeData) {
        this.examData.viewTime = this.viewTimeData;
      } else {

      }
    },
    //在发起考试时呼起隐藏框 并且拉取paperList 试卷列表 注入this.examData.handClassId
    addExamById(id) {
      this.examData.handleClassId = id
      getPaperListApi().then(res => {
        if (res.data.code == 200) {
          // console.info("this.PaperList", res.data.data)
          this.paperList = res.data.data
        }
      })
      console.info("handleClass id：", id)
      this.addExamVisible = true
    },
    //显示添加用户隐藏框
    insertHandleClass() {
      this.addDialogVisible = true;
      let temp = storage.getItem("user").id;
      this.handleClass = {teacherId: temp, school: {}}
    },
    //确定按钮 编辑隐藏框
    async editHandleClose(handleClass) {
      console.info(handleClass)
      let confirm = await this.$myConfirm("确认操作？")
      if (confirm) {
        await updateHandleClassApi(handleClass).then(res => {
          if (res.data.code == 200) {
            notification.ntfCommonSuccess("提示", res.data.msg);
            this.editDialogVisible = false;
            this.getHandleClass()
          }
        })
      }
    },
    //确定按钮 添加隐藏框
    async addHandleClose(handleClass) {
      let confirm = await this.$myConfirm("确认操作？")
      if (confirm) {
        await insertHandleClassApi(handleClass).then(res => {
          console.info("res", res)
          if (res.data.code == 200) {
            notification.ntfCommonSuccess("提示", res.data.msg);
            this.addDialogVisible = false;
            this.getHandleClass()
          }
        })
      }

    },
    /////////////////////////////////////////////////////////////////////
    //每次获取焦点时重新判断state1
    resetCheckHandle() {
      this.checkMajor = false
    },
    //离开焦点后进行state1的判断
    async checkHandle() {
      //等待this.unSelectTemp的值正确响应
      await new Promise(resolve => setTimeout(resolve, 100));
      console.info("checkHandle", this.unSelectTemp)
      if (this.unSelectTemp) {
        this.unSelectTemp = false
      } else {
        let _str = this.handleClass.majorName
        if (subjectData.some(obj => obj.subjectName === this.handleClass.majorName)) {
          this.checkMajor = true;
          console.info("查看匹配是否", this.checkMajor)
        }
        // console.info(this.check)
        //如果一个字符都不符合 清空state1 显示placeholder的内容
        if (!this.checkMajor) {
          this.placeholder = '请输入符合下拉提示框的内容!'
          this.handleClass.majorName = ''
        }
      }


    },
    //点击下拉框会返回选定的内容
    handleSelect(item) {
      // console.info(item)
      this.handleClass.majorName = item.subjectName
      this.unSelectTemp = true
    },
    //subjectData 配合createFilter实现输入下拉索引
    querySearch(queryString, cb) {
      var _subjectData = this.subjectData;
      var results = queryString ? _subjectData.filter(this.createFilter(queryString)) : _subjectData;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        // console.info("restaurant:",restaurant)
        return (restaurant.subjectName.indexOf(queryString) === 0);
      }
    },
    //////////////////////////////////////////////////////////////////////////
    //schoolData 配合createFilter实现输入下拉索引
    resetCheckHandleSchool() {
      this.checkSchoolName = false
    },
    async checkHandleSchool() {
      //等待this.unSelectTemp的值正确响应
      await new Promise(resolve => setTimeout(resolve, 100));
      console.info("checkHandleSchool", this.unSelectTemp)
      //处于下拉选择状态不进行判断
      if (this.unSelectTemp) {
        //重置判断状态
        this.unSelectTemp = false
      } else {
        // console.info("this.handleClass.school.schoolName",this.handleClass.school.schoolName)
        //不处于下拉状态默认进行判断
        let _str = this.handleClass.school.schoolName
        if (schoolInfo.some(obj => obj.schoolName === this.handleClass.school.schoolName)) {
          this.checkSchoolName = true;
          console.info("查看匹配是否", this.checkSchoolName)
        }
        console.info("最终结果school", this.checkSchoolName)
        //如果一个字符都不符合 清空state1 显示placeholder的内容
        if (!this.checkSchoolName) {
          this.placeholder = '请输入符合下拉提示框的内容!'
          this.handleClass.school.schoolName = ''
        }
      }


    },
    //点击下拉框会返回选定的内容
    handleSelectSchool(item) {
      // console.info(item)
      this.handleClass.school.schoolName = item.schoolName
      this.handleClass.school.schoolId = item.id
      //当点击下拉框选择时处于true 不进行 内容判断
      this.unSelectTemp = true
      // console.info("this.unSelectTemp",this.unSelectTemp)

    },

    querySearchSchool(queryString, cb) {
      var _schoolData = this.schoolData;
      var results = queryString ? _schoolData.filter(this.createFilterSchool(queryString)) : _schoolData;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilterSchool(queryString) {
      return (restaurant) => {
        // console.info("restaurant:",restaurant)
        return (restaurant.schoolName.indexOf(queryString) === 0);
      }
    },
    ////////////////////////////////////////////////////////////////

    getHandleClass() {
      let id = storage.getItem("user").id;
      let params = {"id": id}
      getHandleClassApi(params).then(res => {
        // console.info(res)
        if (res.data.code == 200) {
          this.handClassList = res.data.data;
          // console.info("this.handClassList" +
          //     "",this.handClassList)
        }
      })
    },

    handleSizeChange(size) {
      // console.log(size, 'size');
      this.pageSize = size;
      console.log(this.pageSize); //改变每页显示数据条数
    },
    handleCurrentChange(currentPage) {
      // console.log(currentPage, 'currentPage');
      this.currentPage = currentPage;
      console.log(this.currentPage); //点击第几页
    },

    //多选时每列的对象保存在multipleTable中
    handleSelectionChange(val) {
      this.multipleTable = val
    },
    //批量删除
    async deleteByIds() {
      const idArr = [];
      // console.info( this.multipleTable)
      for (let obj of this.multipleTable) {
        idArr.push(obj.id);
      }
      // console.info(idArr)
      if (idArr.length !== 0) {
        let confirm = await this.$myConfirm("确认操作？")
        if (confirm) {
          delHandleClassByIdsApi(idArr).then(res => {
            if (res.data.code == 200) {
              notification.ntfCommonSuccess("提示", res.data.msg);
              this.getHandleClass()
            }
          })
        }
      }
    },
    //单删
    async deleteById(id) {
      let confirm = await this.$myConfirm("确认操作？")
      if (confirm) {
        delHandleClassByIdApi({"id": id}).then(res => {
          if (res.data.code == 200) {
            notification.ntfCommonSuccess("提示", res.data.msg);
            this.getHandleClass()
          }
        })
      }
    },
    //编辑并唤起隐藏框
    editById(id) {
      findByHandleClassId({"id": id}).then(res => {
        this.handleClass = res.data.data;
        console.info("findByHandleClassId", this.handleClass)
        this.editDialogVisible = true;
      })
    }

  },
  created() {
    this.getHandleClass()
  }
}
</script>

<style scoped>

.qSearch {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
  justify-content: start;
//margin-left: 40px; width: 100%;

  .text {
    width: 100px;
  //background-color: #d9dce2; text-align: center; margin-left: 31px;
  }

  .input {
    width: 100%;
  }
}


.name {
  text-overflow: ellipsis;
  overflow: hidden;
}

.addr {
  font-size: 12px;
  color: #b4b4b4;
}


.el-icon-plus {
  font-size: 13px;
}


.topBlock {
  display: flex;
  /*background-color: #42b983;*/
  height: 46px;
  align-items: center;
  justify-content: start;
  /*border-left: 1px solid #e6e6e6;*/
  /*border-right: 1px solid #e6e6e6;*/
  /*background-color: #f5f5f5;*/
  border-radius: 5px;
}

.main {
  height: 700px;
  /*background-color: #42b983;*/
}

.table {
  position: absolute;
  width: 100%;
  top: 45px;
}

.footers {
  position: absolute;
  bottom: -10px;
  width: 100%;
  height: 40px;
  /*background-color: #7c8695;*/
  z-index: 999;
}

</style>